import pygame
import os

class Sound:
    """音效管理器：支持音效优先于背景音乐，音效播放时暂停背景音乐"""
    def __init__(self, base_dir):
        # 标记音效功能是否可用
        self.sound_available = True
        self.bg_music_playing = False  # 背景音乐播放状态
        self.bg_music_path = os.path.join(base_dir, "bgm.mp3")  # 背景音乐路径

        try:
            pygame.mixer.init()
            # 确保混音器有足够的声道同时播放背景音乐和音效
            pygame.mixer.set_num_channels(8)  # 设置8个声道
        except pygame.error as e:
            print(f"⚠️  音效系统初始化失败：{str(e)}")
            self.sound_available = False
            return

        # 音效资源文件夹路径
        self.asset_dir = os.path.join(base_dir, "assets")

        # 预加载所有游戏所需音效
        self.sound_dict = {
            "food_eat": self._load_single_sound("food_eat.wav"),  # 吃食物音效
            "ai_eating": self._load_single_sound("ai_eating.wav"), # --- 新增音效 ---
            "obstacle_hit": self._load_single_sound("obstacle_hit.wav"),  # 碰撞障碍物音效
            "wall_death": self._load_single_sound("wall_death.wav"),  # 撞墙死亡音效
            "speed_up": self._load_single_sound("speed_up.wav"),  # 速度提升特殊食物音效
            "shorten_body": self._load_single_sound("shorten_body.wav"),  # 缩短身体特殊食物音效
            "clear_obstacles":self._load_single_sound("clear_obstacles.wav")  # 清除障碍物特殊食物音效
        }

        # 设置默认音效音量
        self.set_global_volume(0.4)

        # 初始化背景音乐
        self.init_background_music()

    def _load_single_sound(self, filename):
        """加载单个音效文件，带容错处理"""
        sound_path = os.path.join(self.asset_dir, filename)

        if not os.path.exists(sound_path):
            print(f"❌ 音效文件缺失：{sound_path}")
            print(f"   请将 {filename} 放入 {self.asset_dir} 文件夹")
            return None

        try:
            return pygame.mixer.Sound(sound_path)
        except pygame.error as e:
            print(f"⚠️  加载音效 {filename} 失败：{str(e)}")
            return None

    def init_background_music(self):
        """初始化背景音乐"""
        if not self.sound_available:
            return

        try:
            pygame.mixer.music.load(self.bg_music_path)
            pygame.mixer.music.set_volume(0.2)  # 背景音乐音量稍低
            pygame.mixer.music.play(-1)  # 无限循环播放
            self.bg_music_playing = True
            print(f"✅ 背景音乐加载成功：{self.bg_music_path}")
        except pygame.error as e:
            print(f"⚠️  背景音乐加载失败！请将 bgm.mp3 放在正确目录")
            print(f"   错误详情：{str(e)}")
        except Exception as e:
            print(f"⚠️  背景音乐初始化异常：{str(e)}")

    def set_global_volume(self, volume):
        """设置所有音效的全局音量（0.0~1.0）"""
        if not self.sound_available:
            return

        volume = max(0.0, min(1.0, volume))
        for sound in self.sound_dict.values():
            if sound:
                sound.set_volume(volume)

    def play_sound(self, sound_name):
        """播放指定名称的音效，播放时暂停背景音乐，播放完毕后恢复"""
        if not self.sound_available or sound_name not in self.sound_dict:
            return

        sound = self.sound_dict[sound_name]
        if not sound:
            return

        try:
            # 记录背景音乐状态并暂停
            was_playing = self.bg_music_playing

            if was_playing:
                pygame.mixer.music.pause()

            # 播放音效
            channel = sound.play()

            # 如果音效有长度信息，设置定时器在音效结束后恢复背景音乐
            if channel and was_playing:
                # 获取音效长度（毫秒）
                sound_length = int(sound.get_length() * 1000)
                # 注册事件在音效结束后恢复背景音乐
                pygame.time.set_timer(pygame.USEREVENT + 1, sound_length, True)

        except Exception as e:
            print(f"⚠️  播放音效 {sound_name} 失败：{str(e)}")

    def resume_background_music(self):
        """恢复背景音乐播放"""
        if self.sound_available and self.bg_music_playing:
            pygame.mixer.music.unpause()



